package com.hejiale.lease.common.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.hejiale.lease.common.constant.RedisConstant;
import com.hejiale.lease.common.exception.LeaseException;
import com.hejiale.lease.common.result.ResultCodeEnum;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @description: 短信工具类
 * @author: HeJiale
 * @since 2025/3/22 下午2:38
 */

public class SMSUtil {
    private static Client SMSClient;
    private static StringRedisTemplate stringRedisTemplate;

    /**
     * 初始化SMSUtil
     * @param SMSClient
     */
    public static void init(Client SMSClient , StringRedisTemplate stringRedisTemplate) {
        SMSUtil.SMSClient = SMSClient;
        SMSUtil.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 发送短信
     * @param phone
     * @param code
     */
    public static void sendSMS(String phone, String code){
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setTemplateParam("{\"code\":\"" + code + "\"}");

        try {
            SMSClient.sendSms(sendSmsRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成随机验证码
     * @param length
     * @return
     */
    public static String getVerifyCode(int length) {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            builder.append(random.nextInt(10));
        }
        return builder.toString();
    }

    /**
     * 判断验证码是否过期
     * @param phone
     */
    public static void isExpired(String phone){
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;

        // 验证码已过期
        if (!Boolean.TRUE.equals(stringRedisTemplate.hasKey(key))) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
    }

    /**
     * 判断验证码是否发送过于频繁
     * @param phone
     */
    public static void isTooOften(String phone){
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        Long expire = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
        if (expire != null && expire <= 60) {
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }
    }

    /**
     * 判断验证码是否正确
     * @param code
     * @param phone
     */
    public static void isCorrect(String code , String phone){
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        String value = stringRedisTemplate.opsForValue().get(key);
        if (!code.equals(value)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
    }
}
